<!--
  ~
  ~  Copyright (c) 2018-2025, Pactera JinXin Software All rights reserved.
  ~
  -->

<template>
    <div class="madp-user">
        <basic-container>
            <el-row>
                <el-col :span="7">
                    <el-row class="madp-tree-form">
                        <el-input v-model.trim="searchT" maxlength="30" placeholder="输入关键字过滤"></el-input>
                        <el-button v-if="permissions.sys_user_adjust" class="madp-ml10" type="primary" @click="editMember">成员调整</el-button>
                    </el-row>
                    <el-row>
                        <el-tree
                            ref="tree"
                            class="filter-tree"
                            :data="treeData"
                            :props="defaultProps"
                            :filter-node-method="filterNode"
                            @node-click="handleNodeClick"
                            :default-expand-all="false"
                            :expand-on-click-node="false"
                        ></el-tree>
                    </el-row>
                </el-col>
                <el-col :offset="1" :span="16">
                    <el-row>
                        <el-button class="madp-fr madp-ml10" type="primary" @click="searchSubmit(100)">查询</el-button>
                        <el-form class="madp-fr" label-width="80px">
                            <el-form-item label="用户名:">
                                <el-input class="madp-input" v-model.trim="searchT2" clearable placeholder="请输入用户名" maxlength="20"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-row>
                    <el-table v-loading="listLoading" :data="list" :header-cell-style="{ background: '#FAFAFA', color: '#252525' }" stripe border>
                        <el-table-column label="序号" width="70" type="index">
                            <template slot-scope="scope">{{ page.pageSize * (page.currentPage - 1) + scope.$index + 1 }}</template>
                        </el-table-column>
                        <el-table-column label="员工号" prop="username"></el-table-column>
                        <el-table-column label="姓名" prop="name"></el-table-column>
                        <el-table-column label="角色" align="center" prop="role" width="150">
                            <template slot-scope="scope">
                                <div v-if="scope.row.roleList.length > 0">
                                    <span v-for="(role, index) in scope.row.roleList" :key="index">
                                        <el-tag>{{ role.roleName }}</el-tag>
                                    </span>
                                </div>
                                <div v-else>--</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="手机号" width="130" prop="phone">
                            <template slot-scope="scope">
                                <span>{{ scope.row.phone.length > 0 ? scope.row.phone : '--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" width="90" prop="lockFlag">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.lockFlag == '0' ? 'success' : 'info'">{{ scope.row.lockFlag == '0' ? '有效' : '无效' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" width="180" prop="createTime"></el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button type="text" @click="handleView(scope.row)">查看</el-button>
                                <el-button type="text" v-if="showEdit && permissions.sys_user_edit" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="text" v-if="permissions.sys_user_reset" @click="handleReset(scope.row)">重置密码</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 表格分页 -->
                    <el-pagination
                        class="madp-pagination"
                        :current-page="page.currentPage"
                        :page-sizes="[10, 20, 30, 40, 50, 60, 100]"
                        :page-size="page.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="page.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    ></el-pagination>
                </el-col>
            </el-row>
            <el-dialog :title="dialogTitle" :visible.sync="dialogShow" width="55%" v-if="dialogShow" @close="dialogShow = false" :close-on-click-modal="false">
                <el-form label-width="100px" v-model="form">
                    <el-form-item label="id">
                        <el-input disabled v-model="form.userId"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input disabled v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-input disabled v-model="form.deptName"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号">
                        <el-input disabled v-model="form.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="角色" v-if="dialogTitle == '查看'">
                        <div v-if="form.roleList && form.roleList.length > 0">
                            <span v-for="item in form.roleList" :key="item.roleId">{{ item.roleName }}</span>
                        </div>
                        <div v-else>--</div>
                    </el-form-item>
                    <el-form-item label="状态" v-if="dialogTitle == '查看'">
                        <el-input v-model="form.lockFlag1" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="角色" v-if="dialogTitle != '查看'">
                        <el-select v-model="form.roleList" multiple value-key="roleId" :multiple-limit="1">
                            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" v-if="dialogTitle != '查看'">
                        <el-radio v-model="form.lockFlag" label="0" border>正常</el-radio>
                        <el-radio v-model="form.lockFlag" label="9" border>无效</el-radio>
                    </el-form-item>
                    <el-form-item label="创建时间">
                        <el-input disabled v-model="form.createTime"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-input v-model="form.gender1" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="用户类型">
                        <el-input v-model="form.isCorpWxEmp1" disabled></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer">
                    <el-button @click="handleSubmit" type="primary">确定</el-button>
                </span>
            </el-dialog>
            <el-dialog :title="dialogTitle" :visible.sync="dialogShow2" width="55%" top="3%" v-if="dialogShow2" @close="dialogShow2 = false" :close-on-click-modal="false">
                <el-row>
                    <el-col :span="12" class="madp-dialog-left">
                        <el-input v-model.trim="dialogSearchT" placeholder="请输入关键词过滤" show-word-limit maxlength="20">
                            <i slot="suffix" class="el-input__icon el-icon-search"></i>
                        </el-input>
                        <el-tree
                            ref="tree2"
                            class="filter-tree"
                            :data="tree2"
                            :props="defaultProps"
                            node-key="id"
                            :highlight-current="true"
                            :filter-node-method="filterNode"
                            :expand-on-click-node="false"
                            :default-expand-all="false"
                            :load="loadNode"
                            lazy
                            @node-click="handleNodeClick2"
                        >
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <span class="tree-node-icon">
                                    <i v-if="data.leaf" class="el-icon-s-custom"></i>
                                    <i v-else class="el-icon-office-building"></i>
                                </span>
                                <span>{{ node.label }}</span>
                                <span v-show="showCheck(data.id)" class="madp-tree-check">
                                    <i class="el-icon-check"></i>
                                </span>
                            </span>
                        </el-tree>
                    </el-col>
                    <el-col class="madp-list-right" :offset="1" :span="11">
                        <p>已选择的部门、成员</p>
                        <div :key="tag.userId" v-for="tag in curList" class="madp-tag-item">
                            <el-tag closable :disable-transitions="false" @close="handleClose(tag)">{{ tag.name }}</el-tag>
                        </div>
                    </el-col>
                </el-row>
                <span slot="footer">
                    <el-button @click="handleUpdate" type="primary">确定</el-button>
                    <el-button @click="handleCancle">取消</el-button>
                </span>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import { fetchList, fetchLineList, updateLineList, fetchChildrens, resetPwd, putObj } from '@/api/admin/user';
import { deptRoleList } from '@/api/admin/role';
import { fetchTree } from '@/api/admin/dept';
import { mapGetters } from 'vuex';
export default {
    name: 'madp-user',
    data() {
        return {
            showEdit: false, // 显示编辑按钮
            treeData: [], // 表格数据
            // 树组件Props
            defaultProps: {
                children: 'children',
                label: 'name',
                isLeaf: 'leaf'
            },
            list: [], // 表格数据
            listLoading: false, //表格loading
            listLoading2: false,
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10, // 每页显示多少条,
                pageSizes: [10, 20],
                isAsc: false // 是否倒序
            },
            searchT2: '', // 查询输入框文本内容
            searchT: '',
            dialogShow: false, // 弹窗开关
            dialogShow2: false,
            dialogTitle: '', // 弹窗 标题
            form: {}, // 表单对象
            roleList: [], // 角色列表
            clickNode: {}, // 点击节点
            tree2: [],
            dialogSearchT: '',
            selectUserIds: [], // 人员id
            selectLineDeptIds: [], // 部门id
            editId: '' // 调整成员的部门id
        };
    },
    watch: {
        dialogSearchT(val) {
            this.$refs.tree2.filter(val);
        },
        searchT(val) {
            this.$refs.tree.filter(val);
        }
    },
    computed: {
        curList() {
            return [...this.selectLineDeptIds, ...this.selectUserIds];
        },
        ...mapGetters(['permissions'])
    },
    created() {
        this.init();
    },
    methods: {
        editMember() {
            if (this.clickNode[0].deptType === 0) {
                this.$notify.info('请选择条线分支进行成员调整');
                return;
            }
            if (this.clickNode[0].parentId === 0) {
                this.$notify.info('请选择条线下部门进行成员调整');
                return;
            }
            this.dialogShow2 = true;
            this.dialogTitle = '成员调整';
            let id = this.clickNode[0].id;
            this.editId = id;
            fetchChildrens(id).then((response) => {
                if (response.data.code === 0) {
                    let arr1 = response.data.data.users.map((i) => {
                        let obj = {
                            leaf: true,
                            name: i.cname,
                            id: i.userId
                        };
                        return obj;
                    });
                    let arr2 = response.data.data.depts.map((i) => {
                        let obj = {
                            leaf: false,
                            name: i.name,
                            id: i.deptId
                        };
                        return obj;
                    });
                    let arr = [...arr1, ...arr2];
                    this.tree2 = arr;
                }
            });
            fetchLineList(id).then((res) => {
                if (res.data.code != 0) return;
                let arr1 = res.data.data.selectUsers,
                    arr2 = res.data.data.selectDepts;
                this.selectUserIds = arr1.map((i) => {
                    let obj = {
                        id: i.userId,
                        name: i.cname
                    };
                    return obj;
                });
                this.selectLineDeptIds = arr2.map((i) => {
                    let obj = {
                        id: i.deptId,
                        name: i.name
                    };
                    return obj;
                });
            });
        },
        init() {
            fetchTree().then((response) => {
                if (response.data.code === 0) {
                    this.treeData = response.data.data;
                    if (this.treeData.length > 0) {
                        this.clickNode = this.treeData;
                        this.handleNodeClick(this.treeData[0]);
                    }
                }
            });
            deptRoleList().then((res) => {
                if (res.data.code != 0) return;
                this.roleList = res.data.data.filter((i) => i.roleId != 1);
            });
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        handleNodeClick(data) {
            this.listLoading = true;
            this.searchT2 = '';
            this.page.currentPage = 1;
            this.clickNode = [data];
            const tempObj = {
                current: this.page.currentPage,
                size: this.page.pageSize,
                deptId: data.id
            };
            fetchList(tempObj)
                .then((response) => {
                    if (response.data.code === 0) {
                        this.showEdit = data.deptType === 0 ? true : false;
                        this.list = response.data.data.records;
                        this.page.total = response.data.data.total;
                        this.listLoading = false;
                    }
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        handleNodeClick2(data) {
            let { name, id } = data,
                keyArr = ['selectLineDeptIds', 'selectUserIds'];
            this.changeList(keyArr[Number(Boolean(data.leaf))], {
                name,
                id
            });
        },
        changeList(key, obj) {
            let index = -1,
                flag = this[key].some((i, idx) => {
                    if (i.id === obj.id) {
                        index = idx;
                        return true;
                    }
                });
            if (flag) {
                this[key].splice(index, 1);
            } else {
                this[key].push(obj);
            }
        },
        loadNode(node, resolve) {
            if (node.data.id) {
                let id = node.data.id;
                fetchChildrens(id).then((response) => {
                    if (response.data.code === 0) {
                        let arr1 = response.data.data.users.map((i) => {
                            let obj = {
                                leaf: true,
                                name: i.cname,
                                id: i.userId
                            };
                            return obj;
                        });
                        let arr2 = response.data.data.depts.map((i) => {
                            let obj = {
                                leaf: false,
                                name: i.name,
                                id: i.deptId
                            };
                            return obj;
                        });
                        let arr = [...arr1, ...arr2];
                        resolve(arr);
                    }
                });
            }
        },
        searchSubmit() {
            this.getList();
        },
        /**
         * 分页-改变每页记录条数触发查询
         **/
        handleSizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.getList(1);
        },
        /**
         * 分页-改变当前页码记录条数触发查询
         **/
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage;
            this.getList(1);
        },
        getList(data) {
            this.listLoading = true;
            if (!data) {
                this.page.currentPage = 1;
            }
            let obj = {
                current: this.page.currentPage,
                size: this.page.pageSize,
                username: this.searchT2,
                deptId: this.clickNode[0].id
            };
            fetchList(obj)
                .then((response) => {
                    if (response.data.code === 0) {
                        this.list = response.data.data.records;
                        this.page.total = response.data.data.total;
                        this.listLoading = false;
                    }
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        handleView(data) {
            this.dialogShow = true;
            this.dialogTitle = '查看';
            this.form = Object.assign({}, data);
            this.form.lockFlag1 = this.form.lockFlag === '0' ? '有效' : '无效';
            this.form.gender1 = this.form.gender === '1' ? '男' : '女';
            this.form.isCorpWxEmp1 = this.form.isCorpWxEmp ? '企业微信' : '系统';
        },
        handleEdit(data) {
            this.dialogTitle = '编辑';
            this.form = { ...data };
            this.form.gender1 = this.form.gender === '1' ? '男' : '女';
            this.form.isCorpWxEmp1 = this.form.isCorpWxEmp ? '企业微信' : '系统';
            this.dialogShow = true;
        },
        handleReset(data) {
            this.$confirm('是否确认重置' + data.name + '的用户密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    resetPwd(data.userId).then((res) => {
                        if (res.data.code != 0) return;
                        this.$message.success('重置成功');
                        this.handleCancle();
                    });
                })
                .catch(() => {});
        },
        handleSubmit() {
            if (this.dialogTitle == '查看') {
                this.dialogShow = false;
            } else {
                delete this.form.gender1;
                delete this.form.isCorpWxEmp1;
                putObj(this.form).then((res) => {
                    if (res.data.code != 0) return;
                    this.$message.success('编辑成功');
                    this.dialogShow = false;
                    this.getList(1);
                });
            }
        },
        handleClose(data) {
            let index = -1;
            let flag = this.selectLineDeptIds.some((i, idx) => {
                if (i.id === data.id) {
                    index = idx;
                    return true;
                }
            });
            if (flag) {
                this.selectLineDeptIds.splice(index, 1);
            } else {
                this.selectUserIds.some((i, idx) => {
                    if (i.id === data.id) {
                        index = idx;
                        return true;
                    }
                });
                if (index > -1) this.selectUserIds.splice(index, 1);
            }
        },
        showCheck(id) {
            let arr = [...this.selectUserIds, ...this.selectLineDeptIds];
            let flag = arr.some((i) => {
                if (i.id === id) {
                    return true;
                }
            });
            return flag;
        },
        handleCancle() {
            this.dialogShow2 = false;
        },
        handleUpdate() {
            let obj = {
                lineDeptId: this.editId,
                selectLineDeptIds: [],
                selectUserIds: []
            };
            this.selectLineDeptIds.map((i) => {
                obj.selectLineDeptIds.push(i.id);
            });
            this.selectUserIds.map((i) => {
                obj.selectUserIds.push(i.id);
            });
            updateLineList(obj).then((res) => {
                if (res.data.code != 0) return;
                this.$message.success('成员调整成功');
                this.page.currentPage = 1;
                this.handleCancle();
                this.init();
            });
        }
    }
};
</script>
<style lang="scss">
.madp-user {
    height: 100%;
    .madp-tree-form {
        margin-bottom: 8px;
        display: flex;
    }
}
.madp-dialog-left {
    height: 600px;
    overflow: auto;
}
.madp-list-right {
    height: 600px;
    overflow-y: auto;
    p {
        color: #787878;
        font-size: 14px;
    }
}
.madp-checkbox-head {
    width: 100%;
    height: 60px;
    line-height: 60px;
}
.madp-checkbox-item {
    width: 100%;
    height: 60px;
    line-height: 60px;
    padding-left: 20px;
    border-bottom: 1px solid #000;
}
.filter-tree {
    margin-top: 10px;
}
.madp-tag-item {
    margin-top: 2px;
}
.madp-tree-check {
    display: inline-block;
    padding-left: 10px;
}
.el-dialog__body {
    font-size: 16px;
}
.tree-node-icon {
    display: inline-block;
    margin-right: 4px;
    font-size: 20px;
    color: #ed5555;
}
</style>
